package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 页面a标签跳转时回调到该路径，获取code参数，请求token
     * @return
     */
    @GetMapping("/oauth2/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> map=new HashMap<>();
        map.put("client_id","2636917288");
        map.put("client_secret","6a263e9284c6c1a74a62eadacc11b6e2");
        map.put("grant_type","uathorization_code");
        map.put("redirect_uri","http://gulimall.com/oauth2/weibo/success");
        map.put("code",code);
        HttpResponse resp = HttpUtils.doPost("api.weibo.com", "/oauth2/access_toke", "post", null, null, map);
        if(resp.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(resp.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //如果是第一次，自动注册，关联社交帐号uid和自动注册会员
            R r = memberFeignService.oauthlogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo memberRespVo = (MemberRespVo) r.getData("data", new TypeReference<MemberRespVo>(){});
                session.setAttribute("loginUser",memberRespVo);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }
        return "redirect:http://gulimall.com";
    }
}
